require 'digest/sha2'
class User < ActiveRecord::Base

  has_many :categories, :dependent => :destroy
  has_many :expenses, :dependent => :destroy

  acts_as_authorized_user
  acts_as_authorizable

  attr_accessor :password
  attr_accessible :username, :email, :password, :password_confirmation
  attr_locked :username

  before_save :encrypt_password 

  validates_presence_of     :username, :email
  validates_presence_of     :password, :if => :password_required?
  validates_presence_of     :password_confirmation, :if => :password_required?
  validates_format_of       :username, :with => /\A[a-z0-9_]+\Z/i
  validates_format_of       :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_length_of       :password, :within => 6..20, :if => :password_required?
  validates_length_of       :username, :within => 6..32
  validates_length_of       :email, :within => 6..128
  validates_confirmation_of :password, :if => :password_required?
  validates_uniqueness_of   :username, :case_sensitive => false
  validates_uniqueness_of   :email, :case_sensitive => false, :if => Proc.new {|u| !u.deleted_at.blank?}

  # TODO: MAJOR! Revist activation process
  acts_as_state_machine :initial => :passive, :column => :status
  state :passive
  state :pending, :enter => :do_register
  state :notified, :enter => :do_notify
  state :active, :enter => :do_activate
  state :suspended, :enter => :do_suspend
  state :deleted, :enter => :do_delete

  event :register do
    # The guard makes sure we have saved (:before_save filter generates hashed_password)
    transitions :from => :passive, :to => :pending, :guard => Proc.new {|u| !u.hashed_password.blank?}
  end

  event :notify do
    transitions :from => :pending, :to => :notified
  end

  event :activate do
    transitions :from => :notified, :to => :active
  end
  
  event :suspend do
    transitions :from => [:passive, :pending, :notified, :active], :to => :suspended
  end

  event :unsuspend do
    transitions :from => :suspended, :to => :active, :guard => Proc.new {|u| !u.activated_at.blank?}
    transitions :from => :suspended, :to => :pending, :guard => Proc.new {|u| !u.activation_code.blank?}
    transitions :from => :suspended, :to => :passive
  end

  event :delete do
    transitions :from => [:passive, :pending, :notified, :active, :suspended], :to => :deleted
  end

  event :undelete do
    transitions :from => :deleted, :to => :passive
  end

  # The existence of an activation code means they have not activated yet
  def has_activation_code?
    !activation_code.nil?
  end

  # Authenticates a user by their username and unencrypted password.  Returns the user or nil.
  def self.authenticate(username, password)
    u = find :first, :conditions => ['username = ? and status = "active"', username]
    u && u.authenticated?(password) ? u : nil
  end

  # Does hashed_password match the supplied password?
  def authenticated?(password)
    hashed_password == encrypt(password)
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA512.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token = nil
    save(false)
  end

  def forgot_password
    @forgotten_password = true
    self.make_reset_password_code
  end

  # TODO: Do we need this?
  #def pending?
  # @activated
  #end

  def recently_forgot_password?
    @forgotten_password
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at 
  end

  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    remember_me_for 2.weeks
  end

  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end

  def remember_me_until(time)
    self.remember_token_expires_at = time
    self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
    save(false)
  end

  # First update the password_reset_code before setting the 
  #   reset_password flag to avoid duplicate email notifications.
  def reset_password
    update_attributes(:reset_password_code => nil)
    @reset_password = true
  end 

  # Override of to_param
  def to_param
    "#{username}"
  end

  def do_register
    make_activation_code
  end

  def do_notify
    # Deliver registration notification
    UserMailer.deliver_registration(self)
  end

  def do_activate
    @activated = true
    self.suspended_at = nil
    self.activation_code = nil
    self.activated_at = Time.now.utc
    # Deliver activation notification
    UserMailer.deliver_activation(self)
  end

  def do_delete
    self.deleted_at = Time.now.utc
    # Deliver suspension notification
    UserMailer.deliver_deletion(self)
  end

  def do_suspend
    self.suspended_at = Time.now.utc
    # Deliver suspension notification
    UserMailer.deliver_suspension(self)
  end

  # a before_save filter
  def encrypt_password
    return if password.blank?
    self.salt = generate_code if new_record?
    self.hashed_password = encrypt(password)
  end

# a before_save filter
#  def make_users_user
#    if !self.has_role?("User", User)
#      self.has_role("User", User)
#    end
#  end

  def make_activation_code
    self.activation_code = generate_code
  end

  def make_reset_password_code
    self.reset_password_code = generate_code
  end

  def password_required?
    !password.blank?
  end

# helper
  def generate_code
    Digest::SHA256.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  end

end
